package com.example.system.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.commons.core.entity.UserInfo;
import lombok.extern.log4j.Log4j2;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Log4j2
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("执行公共的新增方法，传入数据为{}", JSON.toJSONString(metaObject.getOriginalObject()));
        UserInfo userInfo = (UserInfo) StpUtil.getSession().get("userInfo");
        this.fillStrategy(metaObject, "createTime", LocalDateTime.now())
                .fillStrategy(metaObject, "createUserId", userInfo.getId())
                .fillStrategy(metaObject, "createUserName", userInfo.getUserName())
                .fillStrategy(metaObject, "updateTime", LocalDateTime.now())
                .fillStrategy(metaObject, "updateUserId", userInfo.getId())
                .fillStrategy(metaObject, "updateUserName", userInfo.getUserName())
                .fillStrategy(metaObject, "deleteFlag", false);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("执行公共的更新方法，传入数据为{}", JSON.toJSONString(metaObject.getOriginalObject()));
        UserInfo userInfo = (UserInfo) StpUtil.getSession().get("userInfo");
        this.fillStrategy(metaObject, "updateTime", LocalDateTime.now())
                .fillStrategy(metaObject, "updateUserId", userInfo.getId())
                .fillStrategy(metaObject, "updateUserName", userInfo.getUserName());
    }
}
